<template>
	<div class="product-search-container p-4 space-y-6">
		<!-- 搜索条件栏 -->
		<el-card>
			<el-form inline :model="filters" class="space-x-4">
				<el-form-item label="关键词">
					<el-input v-model="filters.keyword" placeholder="产品名/描述" />
				</el-form-item>
				<el-form-item label="产品类型">
					<el-select v-model="filters.category" placeholder="请选择">
						<el-option v-for="item in categories" :key="item" :label="item" :value="item" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="Search" @click="onSearch">搜索</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<!-- 搜索结果 -->
		<el-card>
			<div class="text-base font-semibold mb-4">搜索结果（共 {{ results.length }} 项）</div>
			<el-row :gutter="20">
				<el-col :span="6" v-for="item in results" :key="item.id">
					<el-card :body-style="{ padding: '12px' }" shadow="hover" @click="toDetail(item.id)"
						class="cursor-pointer">
						<img :src="item.image" class="w-full h-40 object-cover rounded" />
						<div class="mt-2 font-medium">{{ item.name }}</div>
						<div class="text-sm text-gray-500 mt-1">{{ item.category }}</div>
						<div class="text-sm text-gray-700 mt-1">库存：{{ item.stock }}</div>
					</el-card>
				</el-col>
			</el-row>
		</el-card>
	</div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const filters = ref({
	keyword: route.query.keyword || '',
	category: route.query.category || ''
})

const categories = ref(['芯片', '模组', '封装', '制造', '原材料', '检测'])
const results = ref([])

const allProducts = [
	{ id: 1, name: 'AI 控制芯片 A1', category: '芯片', stock: 120, image: 'https://via.placeholder.com/300x160?text=A1' },
	{ id: 2, name: '光电模组 M2', category: '模组', stock: 60, image: 'https://via.placeholder.com/300x160?text=M2' },
	{ id: 3, name: '封装材料 P3', category: '封装', stock: 310, image: 'https://via.placeholder.com/300x160?text=P3' },
	{ id: 4, name: '制造机械零件 Z4', category: '制造', stock: 85, image: 'https://via.placeholder.com/300x160?text=Z4' }
]

const onSearch = () => {
	const keyword = filters.value.keyword.trim().toLowerCase()
	const category = filters.value.category
	results.value = allProducts.filter(p => {
		const matchKeyword = keyword ? p.name.toLowerCase().includes(keyword) : true
		const matchCategory = category ? p.category === category : true
		return matchKeyword && matchCategory
	})
}

const toDetail = (id) => {
	router.push({ name: 'ProductDetail', params: { id } })
}

onMounted(() => {
	onSearch()
})
</script>

<style scoped>
.product-search-container {
	background-color: #f5f7fa;
	min-height: 100vh;
}
</style>